<?php
/*
 * Created on
 * Date: Mar 4, 2008
 * Author: William Yang
 */
require_once(dirname(__FILE__)."/../common/constants.php");
require_once(DB_SESSION_DIR_PATH."/db_pagi_opera.php");

class PagiOperator extends DatabaseOperator {
	protected $cntOfPage;
	protected $search_cond;
	protected $result_set;
	protected $cur_page;
	protected $page_size;
	protected $rec_cnt;
	
	public function __construct () {
		parent::__construct();
		
		$this->cntOfPage	= NULL;
		$this->search_cond	= new SqlCondList();
		$this->result_set	= NULL;
		$this->cur_page		= 0;
		$this->page_size	= 0;
		$this->rec_cnt		= 0;
	}
	
	public function setCondition($condition) {
		if ( $condition != NULL && ( gettype($condition) == gettype(new SqlCondList()) ) )
			$this->search_cond = $condition;
	}
	
	/*
	 * It sets how many pages are queried out.
	 */
	public function setCountOfPage($cnt) {
		$this->cntOfPage = $cnt;
	}
	
	/*
	 * Page number starts from 1.
	 */
	public function go2page($page_num, $page_size, $is_counting = false) {
		$this->cur_page = $page_num;
		$this->page_size = $page_size;
		
		if ($is_counting && $page_size != NULL) {
			$target[] = "count(*)"; 
			$result = $this->select($this->search_cond, $target);
			$this->rec_cnt = $result[0]["count(*)"];
			
			if (($this->rec_cnt % $page_size) == 0)
				$this->cntOfPage = intval($this->rec_cnt / $page_size);
			else
				$this->cntOfPage = intval($this->rec_cnt / $page_size) + 1;
		}
		
		if ($page_size != NULL)
			$limit = new SqlLimit(($page_num - 1) * $page_size, $page_size);
		
		if ($this->search_cond != NULL)
			$this->search_cond->add_limit($limit);
		
		$this->result_set = $this->select($this->search_cond);
	}
	
	public function getResultSet() {
		return $this->result_set;
	}
	
	public function getCountOfPage() {
		return $this->cntOfPage;
	}
	
	public function getCountOfRecord() {
		return $this->rec_cnt;
	}
}
?>
